<template>
  <div class="stats-cards-container">
    <!-- 会员用户卡片 -->
    <el-card class="stats-card" shadow="hover">
      <div class="card-content">
        <div class="card-title">会员用户</div>
        <div class="card-value">{{ memberCount }}</div>
        <div class="card-header">
          <el-icon class="user-icon"><User /></el-icon>
          <el-icon class="user-icon"><User /></el-icon>
          <el-icon class="user-icon"><User /></el-icon>
          <el-icon class="user-icon"><User /></el-icon>
          <el-icon class="user-icon"><User /></el-icon>
        </div>
        <div class="card-ratio">占比 {{ memberRatio }}</div>
      </div>
    </el-card>

    <!-- 非会员用户卡片 -->
    <el-card class="stats-card" shadow="hover">
      <div class="card-content">
        <div class="card-title">非会员用户</div>
        <div class="card-value">{{ nonMemberCount }}</div>
        <div class="card-header">
          <el-icon class="user-icon non-member"><User /></el-icon>
          <el-icon class="user-icon non-member"><User /></el-icon>
          <el-icon class="user-icon non-member"><User /></el-icon>
          <el-icon class="user-icon non-member"><User /></el-icon>
          <el-icon class="user-icon non-member"><User /></el-icon>
        </div>
        <div class="card-ratio">占比 {{ nonMemberRatio }}</div>
      </div>
    </el-card>

    <!-- 日活用户卡片 -->
    <el-card class="stats-card" shadow="hover">
      <div class="card-content">
        <div class="card-title">日活用户</div>
        <div class="card-value">4,560</div>
        <div class="card-ratio">
          <span>占比 45%</span>
          <span class="trend down">日环比 ▼ 11%</span>
        </div>
      </div>
    </el-card>

    <!-- 月活用户卡片 -->
    <el-card class="stats-card" shadow="hover">
      <div class="card-content">
        <div class="card-title">月活用户</div>
        <div class="card-value">6,678</div>
        <div class="card-ratio">
          <span>占比 60%</span>
          <span class="trend down">周同比 ▼ 12%</span>
        </div>
      </div>
    </el-card>
  </div>

  <!-- 地区表格 -->
  <el-card class="region-card">
    <template #header>
      <div class="card-header-title">各地区分布</div>
    </template>

    <el-table
        :data="tableRows"
        style="width: 100%"
        class="region-table no-border"
        header-cell-class-name="custom-header"
    >
      <el-table-column
          v-for="(col, index) in columns"
          :key="index"
          :prop="col.prop"
          :label="col.label"
          align="center"
      />
    </el-table>
  </el-card>

  <!-- 各时段在线用户折线图 -->
  <el-card class="line-chart-card">
    <template #header>
      <div class="card-header-title">各时间段活跃在线用户</div>
    </template>

    <div class="toolbar">
      <el-button-group>
        <el-button type="primary" size="small" @click="setRange('yesterday')">昨天</el-button>
        <el-button size="small" @click="setRange('7')">最近7天</el-button>
        <el-button size="small" @click="setRange('30')">最近30天</el-button>
      </el-button-group>
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          size="small"
          class="date-picker"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
      />
    </div>

    <div class="chart-body">
      <v-chart class="chart" :option="chartOptions" autoresize />

      <div class="summary">
        <div class="count">
          <div class="label">昨日活跃用户数</div>
          <div class="value">4560</div>
        </div>
        <div class="hot-period">
          <div class="label">用户最佳活跃时段</div>
          <div class="value">16:00-17:00<br />20:00-21:00</div>
        </div>
      </div>
    </div>
  </el-card>

  <el-card class="gender-card">
    <template #header>
      <div class="card-header-title">性别比例</div>
    </template>

    <div class="gender-bar">
      <div
          class="bar female"
          :style="{ width: femalePercentage + '%' }"
      ></div>
      <div
          class="bar male"
          :style="{ width: malePercentage + '%' }"
      ></div>
    </div>

    <div class="gender-legend">
      <div class="legend-item">
        <span class="legend-color female"></span> 女 ({{ femalePercentage }}%)
      </div>
      <div class="legend-item">
        <span class="legend-color male"></span> 男 ({{ malePercentage }}%)
      </div>
    </div>
  </el-card>
  <!-- 年龄分布区域 -->
  <div class="age-distribution">
    <el-card shadow="hover" class="chart-card">
      <template #header>
        <div class="card-header">
          <span>年龄分布</span>
        </div>
      </template>

      <!-- 图表和文本说明 -->
      <div class="age-chart-wrapper">
        <!-- 图表 -->
        <div ref="chartRef" class="chart"></div>

        <!-- 文本说明 -->
        <div class="age-text-list">
          <ul>
            <li v-for="(item, index) in ageData" :key="index">
              年龄段: {{ item.ageRange }}<br />
              用户占比: {{ item.percentage }}%
            </li>
          </ul>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import { use } from 'echarts/core'
import VChart from 'vue-echarts'
import * as echarts from 'echarts';
import {
  CanvasRenderer
} from 'echarts/renderers'
import {
  LineChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import axios from "axios";

use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
])

const dateRange = ref([])

const setRange = (type) => {
  // 这里只是示例，不做实际日期处理
  console.log('选择范围：', type)
}

const chartOptions = {
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['0', '2', '4', '6', '8', '10', '12', '14', '16', '18', '20', '22', '24']
  },
  yAxis: {
    type: 'value'
  },
  grid: {
    left: '3%',
    right: '30%',
    bottom: '8%',
    containLabel: true
  },
  series: [
    {
      data: [1600, 1400, 1200, 1100, 1500, 1600, 1800, 1700, 1900, 2100, 2300, 2500, 1600],
      type: 'line',
      smooth: true,
      symbol: 'circle',
      lineStyle: {
        color: '#409EFF'
      },
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
}
const columns = [
  { prop: 'region', label: '地区' },
  { prop: 'userCount', label: '人数' }
]

const rawData = ref()
const regionStatistics = () => {
  axios.get("/userCount/regionStatistics").then(resp => {
    rawData.value = resp.data;
    tableRows.value = resp.data
  })
}

const tableRows = ref([])




const initChart = () => {
  const chart = echarts.init(chartRef.value);
  const option = {
    title: {
      text: '年龄分布'
    },
    tooltip: {},
    xAxis: {
      data: ageData.map(item => item.ageRange)
    },
    yAxis: {},
    series: [{
      name: '用户数量',
      type: 'bar',
      data: ageData.map(item => item.percentage * 100)
    }]
  };
  chart.setOption(option);
};

onMounted(() => {
  fetchAgeDistribution();
  fetchGenderStatistics();
  regionStatistics();
  fetchUserStats()

});
// ====================================================
const memberCount = ref(0)
const nonMemberCount = ref(0)
const memberRatio = ref('0%')
const nonMemberRatio = ref('0%')
const fetchUserStats = async () => {
  try {
    const res = await axios.get('/userCount/statistics')
    const data = res.data

    memberCount.value = data.memberCount
    nonMemberCount.value = data.nonMemberCount
    const total = data.total || 1  // 防止除以 0

    memberRatio.value = ((data.memberCount / total) * 100).toFixed(2) + '%'
    nonMemberRatio.value = ((data.nonMemberCount / total) * 100).toFixed(2) + '%'
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}
// ====================================================

// ===========================================================
const genderData = ref({ male: 0, female: 0 })

const malePercentage = computed(() => {
  const total = genderData.value.male + genderData.value.female
  return total === 0 ? 0 : ((genderData.value.male / total) * 100).toFixed(1)
})

const femalePercentage = computed(() => {
  const total = genderData.value.male + genderData.value.female
  return total === 0 ? 0 : ((genderData.value.female / total) * 100).toFixed(1)
})

const fetchGenderStatistics = () => {
  axios.get("/userCount/genderStatistics").then(resp => {
    genderData.value = resp.data
  })
}
// ===========================================================
// ===========================================================
const ageData = ref([]) // [{ ageRange: '0-18', percentage: 25 }, ...]

const chartRef = ref(null)

const fetchAgeDistribution = async () => {
  try {
    const resp = await axios.get('/userCount/ageDistribution')
    ageData.value = resp.data
    renderAgeChart()
  } catch (e) {
    console.error('获取年龄分布失败:', e)
  }
}

const renderAgeChart = () => {
  const chart = echarts.init(chartRef.value)

  chart.setOption({
    title: {
      text: '年龄分布图',
      left: 'center',
      textStyle: { fontSize: 16 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    xAxis: {
      type: 'category',
      data: ageData.value.map(item => item.ageRange)
    },
    yAxis: {
      type: 'value',
      name: '占比（%）',
      min: 0,
      max: 100
    },
    series: [
      {
        name: '用户占比',
        type: 'bar',
        data: ageData.value.map(item => item.percentage),
        itemStyle: {
          color: '#73C0DE',
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  })
}

onMounted(fetchAgeDistribution)

// ===========================================================
</script>

<style scoped>

.age-chart-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-top: 12px;
}

.age-chart-wrapper .chart {
  width: 65%;
  height: 300px;
}

.age-text-list {
  width: 30%;
  padding-left: 16px;
  font-size: 14px;
  color: #333;
}

.age-text-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.age-text-list li {
  margin-bottom: 12px;
  line-height: 1.6;
}
.age-distribution {
  padding: 20px;
}

.chart-card {
  width: 100%;
}

.chart {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-list ul {
  list-style-type: none;
  padding: 0;
}

.data-list li {
  margin-bottom: 10px;
}
.gender-card {
  margin: 20px;
  padding: 16px;
}

.card-header-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.gender-bar {
  display: flex;
  height: 20px;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 12px;
  background-color: #f0f0f0;
}

.bar {
  height: 100%;
}

.female {
  background-color: #ec6c83;
}

.male {
  background-color: #0099ff;
}

.gender-legend {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  font-size: 14px;
  color: #333;
}

.legend-item {
  display: flex;
  align-items: center;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  margin-right: 6px;
  border-radius: 2px;
}

.legend-color.female {
  background-color: #ec6c83;
}

.legend-color.male {
  background-color: #0099ff;
}
.line-chart-card {
  margin: 20px;
  padding: 16px;
  border-radius: 8px;
}

.card-header-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.chart-body {
  display: flex;
  position: relative;
}

.chart {
  width: 70%;
  height: 300px;
}

.summary {
  width: 30%;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-size: 14px;
  color: #666;
}

.count .value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-top: 4px;
}

.hot-period .value {
  margin-top: 4px;
  line-height: 1.6;
}
/* 卡片区域 */
.stats-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  padding: 20px;
}

.stats-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 16px;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.card-ratio {
  font-size: 12px;
  color: #888;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.trend.down {
  color: #f56c6c;
  background-color: #fef0f0;
}

.trend.up {
  color: #67c23a;
  background-color: #f0f9eb;
}

/* 图标样式 */
.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.user-icon {
  font-size: 18px;
  color: #409eff;
  background: #ecf5ff;
  padding: 6px;
  border-radius: 50%;
}

.user-icon.non-member {
  color: #67c23a;
  background: #f0f9eb;
}

/* 地区表格样式 */
.region-card {
  margin: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.card-header-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  padding: 10px 0;
}

/* 表格无边框 */
.region-table ::v-deep .el-table__inner-wrapper {
  border: none !important;
}

/* 表头浅灰色 */
.region-table ::v-deep .el-table__header {
  background-color: #f5f7fa !important;
}

/* 表格列宽平均 */
.region-table ::v-deep .el-table__cell {
  width: auto !important;
  flex: 1;
  white-space: nowrap;
}
</style>